package org.example.utils;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.example.common.LoginVo;


import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class JWTUtils {


    //创建token
    //传入userid
    public static String createToken(String userId, String userName, String permission) {
        //存储token主要内容
        Map<String, String> map = new HashMap<>();
        map.put("userName", userName);
        map.put("userId", userId);
        map.put("permission", permission);

        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.SECOND, 24 * 60 * 60 * 7);
        JwtBuilder builder = Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setSubject(JSONUtils.toJSONString(map))
                .setIssuedAt(new Date())
                .setExpiration(calendar.getTime())
                .signWith(SignatureAlgorithm.HS256, "cat_zlj");
        return builder.compact();
    }

    //校验jwt
    public static LoginVo parseToken(String token) {
        try {
            String strToken = Jwts.parser()
                    .setSigningKey("cat_zlj")
                    .parseClaimsJws(token)
                    .getBody().getSubject();
            if (!StringUtils.isBlank(strToken)) {
                LoginVo loginVo = JSON.parseObject(strToken, LoginVo.class);
                return loginVo;
            }
        } catch (Exception e) {
            log.error("jwt match error:{}", e);
            return null;
        }
        return null;
    }

    public static String createToken(String userName) {
        //存储token主要内容
        Map<String, String> map = new HashMap<>();
        map.put("userName", userName);

        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.SECOND, 24 * 60 * 60 * 7);
        JwtBuilder builder = Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setSubject(JSONUtils.toJSONString(map))
                .setIssuedAt(new Date())
                .setExpiration(calendar.getTime())
                .signWith(SignatureAlgorithm.HS256, "cat_zlj");
        return builder.compact();

    }
}

